<?php

declare(strict_types=1);

namespace app\core\DB;


use app\core\Db as MainDB;
use app\core\DB\Interfaces\IDb;
use app\core\DB\Interfaces\IStatement;

class Db implements IDb
{
    public  $db=null;
   
    public static $instance=null;
    public function __construct(){
        $this->db=MainDB::getInstance();
    }
    public static function getInstance(){
        if(!static::$instance){
            static::$instance=new Static;
        }
        static::setConnection();
        return static::$instance;
    }

    /**
     * 预处理sql
     *
     * @param string $sql
     * @return IStatement
     */
    public static function prepare(string $sql){
        return  DBPool::get()['pdo']->prepare($sql);
    }
    public static function lastInsertId(){
       return DBPool::get()['pdo']->lastInsertId();
    }
    public static function setConnection(){
        if(!DBPool::get()){
            DBPool::put([
                'pdo'=>static::$instance->db->getConnection()
            ]);
        }
    }
    public function beginTransaction(){
        DBPool::get()['pdo']->beginTransaction();
    }
    public function commit(){
        $c= DBPool::get()['pdo']->commit();
       
    }
    public function rollBack(){
        $inTransaction=DBPool::get()['pdo']->inTransaction();
        if($inTransaction){
            DBPool::get()['pdo']->rollBack();
        }
    }

    public function getDBPool(){
        return DBPool::get();
    }
    public function release($conn=null){
        static::$instance->db->close(DBPool::get()['pdo']);
    }
}
